package org.biubiu0002.baiblog.im.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @Author: biubiu0002
 * @Date: 2022/10/24 23:17
 **/
@Component
@Slf4j
public class RabbitMqConfig {

    @Autowired
    private ConnectionFactory connectionFactory;

    public static final String SEND_CHAT_MSG_EXCHANGE = "baiblog.im.sendChatMsg.exchange";

    public static final String SEND_CHAT_MSG_ROUTING_KEY = "#";

    public static final String SEND_CHAT_MSG_QUEUE = "baiblog.im.sendChatMsg.queue";


    @Bean("sendChatMsgExchange")
    public Exchange sendChatMsgExchange(){
        return ExchangeBuilder.topicExchange(SEND_CHAT_MSG_EXCHANGE).build();
    }

    @Bean("sendChatMsgQueue")
    public Queue sendChatMsgQueue(){
        return new Queue(SEND_CHAT_MSG_QUEUE,true,false,false);
    }

    @Bean("chatMsgBinding")
    public Binding chatMsgBinding(@Qualifier("sendChatMsgExchange")Exchange exchange,
                                  @Qualifier("sendChatMsgQueue")Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with(SEND_CHAT_MSG_ROUTING_KEY).noargs();
    }



    @Bean
    public RabbitTemplate rabbitTemplate(){
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        //生产者-> MQ Broker 确认机制
        rabbitTemplate.setConfirmCallback((correlationData, ack, s) -> {
            if (!ack) {
                log.info("[发送失败] correlationData:{} cause:{}", correlationData ,s);
            }
        });
        //设置mandatory标志说明开启了消息故障检测模式
        rabbitTemplate.setMandatory(true);
        //MQ Broker ->消费者队列 退回机制
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) ->{
            log.warn("[消息发送失败] replyCode:{} message:{} ",replyCode,message);
        });
        return rabbitTemplate;
    }

}
